//
//  InventoryViewController.m
//  WestAir
//
//  Created by 张燕枭 on 16/9/10.
//  Copyright © 2016年 Henry. All rights reserved.
//

#import "InventoryViewController.h"
#import "SellingViewController.h"
#import "PickingInventory.h"
#import "Invertory.h"
#import "AddInventoryViewController.h"

@interface InventoryViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    __weak IBOutlet UITableView *_tableView;
    UITextField  *textNumBer;
    
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewHeight;

@property (weak, nonatomic) IBOutlet UIButton *btnSubmit;

@property (weak, nonatomic) IBOutlet UIButton *btnCancel;

@property(nonatomic,strong)NSMutableArray  *arrMainData;

@property (weak, nonatomic) IBOutlet UILabel *lableTitle;

@property (weak, nonatomic) IBOutlet UILabel *lablePeiSong;
@property (weak, nonatomic) IBOutlet UILabel *lablePanDian;

@end

@implementation InventoryViewController
@synthesize  btnSubmit,btnCancel,arrMainData ;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self  initDataAndUI];
    

    if (self.saleType==saleAfter) {
        
        self.title=@"回收盘点";
        self.lablePanDian.text=@"实回收";
        self.lablePeiSong.text=@"应回收";
    }

    self.lableTitle.text=  self.title;
}

-(void)initDataAndUI{
    
    [_tableView setTranslatesAutoresizingMaskIntoConstraints:NO];
   
    arrMainData=[NSMutableArray new];
    
    VIEW_CORNER(btnSubmit, buttonCorner21);
    btnSubmit.backgroundColor=NORMAL_BULUE_COLOR;
    
    VIEW_CORNER(btnCancel,buttonCorner21);
    btnCancel.layer.masksToBounds=YES;
    btnCancel.layer.borderColor=NORMAL_BULUE_COLOR.CGColor;
    btnCancel.layer.borderWidth=1.0;

    [self   requetData];
    
    VIEW_CORNER(self.viewBG, 4.0);
    
    HangBanInfo  *hangBan=[HangBanInfo currentHangBan];
    
    if (self.saleType==saleAfter&&[hangBan.FIsInventoryHS  isEqualToString:@"1"]) {
        self.btnAdd.hidden=YES;
        self.ViewBottom.hidden=YES;
    }
    
   
}

-(void)requetData{

    
    HangBanInfo  *hangBanInfo=[HangBanInfo  currentHangBan];
    NSString  *FFLIGHTNUMBER=hangBanInfo.FFLIGHTNUMBER;
    NSString  *FFLIGHTDATE=hangBanInfo.FFLIGHTDATE;
    
    
    NSDictionary  *dicParama=@{@"FNUMBER":FFLIGHTNUMBER,@"FFLIGHTDATE":FFLIGHTDATE};
    NSDictionary  *dicJson= [CMCCIOTIGUnity   getRequestJson:dicParama];

    
    [[NetworkFactory  alloc]  startPostRequestWithURL:self.saleType==startSales?GETINVENTORY:GETINVENTORY_BACK  andPostValues:dicJson andSuccessBlock:^(NSDictionary *responseJson) {
        
       
        [arrMainData  removeAllObjects];
       
        
        if ([responseJson[@"IsSuccess"]  integerValue]==1) {
            
            NSArray  *arrData;
            if ([responseJson[@"data"]  isKindOfClass:[NSArray class]]) {
                arrData=[responseJson[@"data"]  mutableCopy] ;
            }
            else{
            
                arrData=@[];
            }
          

          if (!arrData.count) {
                _btnAdd.hidden=YES   ;
              _ViewBottom.hidden=YES;
               [self performSegueWithIdentifier:@"SellingViewController" sender:@"SellingViewController" ];
              
          }
            
          [arrData  enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
              
            NSDictionary  *dicDataParama=obj;
            Invertory  *invertory=[[Invertory  alloc]  init];
        
              if(self.saleType==startSales){
              invertory.FDispatchQty=[STRING_FORMAT(dicDataParama[@"FDispatchQty"])  integerValue ];
                  invertory.FInventoryQty=[STRING_FORMAT(dicDataParama[@"FDispatchQty"])  integerValue ];
              }
              else{
              
                  invertory.FDispatchQty=[STRING_FORMAT(dicDataParama[@"FInventoryQty"])  integerValue ];
                  invertory.FInventoryQty=[STRING_FORMAT(dicDataParama[@"FInventoryQty"])  integerValue ];
              }
              
           invertory.FName=STRING_FORMAT(dicDataParama[@"FName"]);
           invertory.FNumber=STRING_FORMAT(dicDataParama[@"FNumber"]) ;
            invertory.ID=[STRING_FORMAT(dicDataParama[@"ID"])  integerValue];
        invertory.InvoiceGoodNo=STRING_FORMAT(dicDataParama[@"InvoiceGoodNo"]);


            [arrMainData  addObject:invertory];
              
              ;
          }];
    
            [self  resetFrame:arrMainData.count];
           
        }
        else{
            
            _btnAdd.hidden=YES ;
           
            
        }
         [_tableView  reloadData];
        
        
    } andFailBlock:^(NSError *error) {
         _btnAdd.hidden=YES ;
         [arrMainData  removeAllObjects];
         [_tableView  reloadData];
        
    } ];
    



}

#pragma mark Tableview Deleget

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arrMainData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    PickingInventory   *cell=[tableView dequeueReusableCellWithIdentifier:@"InventoryListPanDianCell"];
     HangBanInfo  *hangBan=[HangBanInfo currentHangBan];
    if (self.saleType==saleAfter&&[hangBan.FIsInventoryHS  isEqualToString:@"1"]) {
        cell.selectionStyle=UITableViewCellSelectionStyleNone ;
    }
    
   Invertory   *invertory=arrMainData[indexPath.row];

   cell.lableShopName.text=invertory.FName;
    cell.PeiSongNum.text=[NSString  stringWithFormat:@"%ld",(long)invertory.FDispatchQty]  ;
    
   cell.lablePanDianNum.text=[NSString  stringWithFormat:@"%ld",(long)invertory.FInventoryQty];
    
   return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    HangBanInfo  *hangBan=[HangBanInfo currentHangBan];

    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
   
    if (self.saleType==saleAfter&&[hangBan.FIsInventoryHS  isEqualToString:@"1"]) {
        return;
    }


    Invertory *invertory=arrMainData[indexPath.row];
    
    [CMCCIOTTipsCenter  showAlertTextFieldTitle:@"修改数量" message:@"" andTFOne:^(UITextField * _Nullable textField) {
          
          UIView  *leftView=[[UIView alloc]  initWithFrame:CGRectMake(0, 0, 10, 10)]          ;
          textField.leftView=leftView;
          textField.leftViewMode=UITextFieldViewModeAlways;
          textField.keyboardType=UIKeyboardTypeNumberPad ;
         [[NSNotificationCenter  defaultCenter]  addObserver:self selector:@selector(textFieldChange:) name:UITextFieldTextDidChangeNotification object:textField];
        textNumBer=textField;
        textField.text=[NSString stringWithFormat:@"%ld",(long)invertory.FInventoryQty] ;
          
          
      } andTFTwo:nil cancelTitle:@"取消" cancelBlock:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
          
          
          ;
      } quireTitle:@"确定" quireBlock:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
          
          if (textNumBer.text.length) {
              NSString  *shopNumber= textNumBer.text;
              Invertory *invertory=arrMainData[indexPath.row];
              invertory.FInventoryQty=[shopNumber  integerValue];
              
              [arrMainData  replaceObjectAtIndex:indexPath.row withObject:invertory];
              
              [tableView  reloadData];

          }
        ;
      }];

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
  
}


- (IBAction)cancel:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma  mark  点击事件

- (IBAction)popBack:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
    
    
}


-(void)textFieldChange:(NSNotification  *)notification{

    UITextField  *textField=[notification   object ];
    if (textField.text.length>6) {
        textField.text=[textField.text substringToIndex:6];
    }

}


- (IBAction)subBtn:(id)sender {

    if (!arrMainData.count) {
        return;
    }
    
    NSMutableDictionary  *dicParama=[[NSMutableDictionary  alloc]  init];
    
 
    HangBanInfo  *hangBanInfo=[HangBanInfo  currentHangBan];
    NSString  *FFLIGHTNUMBER=hangBanInfo.FFLIGHTNUMBER;
    NSString  *FFLIGHTDATE=hangBanInfo.FFLIGHTDATE;
    
    [dicParama  setObject:FFLIGHTNUMBER forKey:@"FFLIGHTNUMBER"];
    [dicParama  setObject:FFLIGHTDATE forKey:@"FFLIGHTDATE"];
    
    [dicParama setObject:[NSNumber numberWithInteger:hangBanInfo.FID ] forKey:@"FID"];
    
    Invertory  *vertory=arrMainData[0];
    [dicParama  setObject:vertory.InvoiceGoodNo forKey:@"InvoiceGoodNo"];
    
    MemberList  *currentMember=[MemberList currentUsinfo];
    [dicParama  setObject:currentMember.userAccount  forKey:@"userAccount"];
    
    //  售前1  售后2
    if (self.saleType==startSales ){
        [dicParama setObject:@"1" forKey:@"FInventoryType"];
    }
    else{
        [dicParama setObject:@"2" forKey:@"FInventoryType"];
    }
    
    NSMutableArray *arrData=[NSMutableArray  new];
    for (int i=0; i<arrMainData.count; i++) {
        
        Invertory  *verTem=arrMainData[i];
        
        NSDictionary  *dicTem=@{@"FDispatchQty":[NSNumber numberWithInteger:verTem.FDispatchQty],@"FInventoryQty":[NSNumber numberWithInteger:verTem.FInventoryQty],@"FName":verTem.FName,@"FNumber":verTem.FNumber,@"ID":[NSString stringWithFormat:@"%ld",(long)verTem.ID],@"InvoiceGoodNo":verTem.InvoiceGoodNo};
        [arrData  addObject:dicTem];
    }
    
    [dicParama  setObject:arrData forKey:@"list"];
     NSDictionary  *desStr= [CMCCIOTIGUnity   getRequestJson:dicParama];
    
    ;
     NSData *dataJson=[NSJSONSerialization dataWithJSONObject:desStr options:0 error:nil];
    NSString *strJson=[[NSString alloc] initWithData:dataJson encoding:NSUTF8StringEncoding];
    
    [[NetworkFactory  alloc]  startPostRequestWithURL:SETINVENTORY andPostValues:desStr andSuccessBlock:^(NSDictionary *responseJson) {
        
        if ([responseJson[@"IsSuccess"]  integerValue]==1) {
        
            if (self.saleType==startSales) {
                
                HangBanInfo  *hangBan= [HangBanInfo  currentHangBan];
                hangBan.FIsInventory=@"1";
                [self performSegueWithIdentifier:@"SellingViewController" sender:@"SellingViewController" ];
            }
            else{
                HangBanInfo  *hangBan=[HangBanInfo currentHangBan];
                hangBan.FIsInventoryHS=@"1";

                [self.navigationController  popViewControllerAnimated:YES];
            }
           
             [CMCCIOTTipsCenter  showSuccessWithStatus:responseJson[@"message"]];
        }
        
        
    } andFailBlock:^(NSError *error) {
        
         
        
    } ];
    


    
}
- (IBAction)addInvertory:(id)sender {
    
    [self performSegueWithIdentifier:@"addInventory" sender:@"addInventory" ];
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender NS_AVAILABLE_IOS(5_0){
   
    
    
    
    
    if([sender  isEqualToString:@"addInventory"]){
    
        AddInventoryViewController  *addInvertory=segue.destinationViewController;
        
        addInvertory.vertoryBlock=^(NSDictionary *dicData){
        
            NSDictionary  *dicParama=dicData;
            
            Invertory  *vertory=[[Invertory  alloc]  init];
            vertory.FDispatchQty=0;
            vertory.FInventoryQty=0;
            vertory.FName=STRING_FORMAT(dicParama[@"FName"]);
            vertory.FNumber=STRING_FORMAT(dicParama[@"FNumber"]);
            vertory.ID=[dicParama[@"FID"]  integerValue];
            vertory.InvoiceGoodNo=@"";
            
            __block  BOOL  isHas=NO;
            
            [arrMainData enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                Invertory  *vertoryTem=(Invertory  *)obj;
                if(vertoryTem.ID== vertory.ID){
                    isHas=YES;
                    *stop=YES;
                
                }
                ;
                
            }];
            
            isHas?nil:[arrMainData  addObject:vertory];
            [self  resetFrame:arrMainData.count];
            
            [_tableView  reloadData];
            
        };
       
     
    }
    else{
    
    
    
    
        
        
    }


}

-(void)resetFrame:(NSInteger )index{

    
    HangBanInfo  *hangBan=[HangBanInfo currentHangBan];
    
     float maxHeight=0;
    
    if (self.saleType==saleAfter&&[hangBan.FIsInventoryHS  isEqualToString:@"1"]) {
       
        self.viewHeight.constant=index*45+35;
         maxHeight=SCREEN_HEIGHT-104;
    }
    else{
         self.viewHeight.constant=index*45+80;
         maxHeight=SCREEN_HEIGHT-175;
    }

    _tableView.scrollEnabled=NO;

    
    if (self.viewHeight.constant>maxHeight) {
        
        self.viewHeight.constant=maxHeight;
        _tableView.scrollEnabled=YES;
    }
   

}




@end
